﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace QZoneMessage
{
    public partial class Form1 : Form
    {
        public enum LogLevel
        {
            Debug = 0,
            Info = 1,
            Warn = 2,
            Error = 3,
        }
        private bool start = false;

        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;

        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            //webBrowser1.Navigate(Application.StartupPath + @"\Test.html");
            string qzoneurl = "http://qzone.qq.com/";
            WelcomeMessage();
            webBrowser1.Navigate(qzoneurl);

            regedit.REGISTERED = regedit.Judge_Whether_Registered();
            if (regedit.REGISTERED)
            {
                regedit.VisitCount = 10000000;
                RegeToolStripMenuItem.Text = "关于";
                RegeToolStripMenuItem.ForeColor = System.Drawing.Color.Black;
            }
            else
            {
                regedit.VisitCount = 10;
            }
        }

        #region buttons
        Element el = new Element();
        private void button1_Click(object sender, EventArgs e)
        {
            Random ro = new Random();
            string test = ro.Next().ToString();
            el.Write_value(el.GetElement_Name(webBrowser1, "QM_334_Accessory_TA"), test);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string qzoneurl2 = "http://165501809.qzone.qq.com/";
            webBrowser1.Navigate(qzoneurl2);
            Thread.Sleep(3000);
            Element ex1 = new Element();
            HtmlElement TestArea = ex1.GetElement_Id(webBrowser1, "QM_334_Accessory_TA");
            HtmlElement SubmitBtn = ex1.GetElement_Id(webBrowser1, "QM_334_Accessory_SubmitBTN");
            if (TestArea != null && SubmitBtn != null)
            {
                ex1.Write_value(TestArea, "你好");
                Thread.Sleep(1000);
                ex1.Btn_click(SubmitBtn, "click");
            }

            //el.Write_value(el.GetElement_Id(webBrowser1, "password"), "123456");
        }
        private void button3_Click(object sender, EventArgs e)
        {
            el.Btn_click(el.GetElement_Id(webBrowser1, "QM_334_Accessory_SubmitBTN"), "click");//方法用的按钮click
        }
        private void button4_Click(object sender, EventArgs e)
        {
            HtmlElement TestArea = this.webBrowser1.Document.GetElementById("QM_334_Accessory_TA");
            //el.Btn_click(el.GetElement_Form(webBrowser1, "form1"), "submit");//先获取表单，再调用表单的submit方法
        }
        #endregion

        #region delegate
        private delegate void submitMessage_dg();
        private void submitMessage()
        {
            string content = string.Empty;

            if (regedit.REGISTERED)
            {
                content = textBox1.Text;
            }
            else
	        {
                content = textBox1.Text + "http://t.cn/zlwbZg9";
            }

            Element ex1 = new Element();
            HtmlElement TestArea = ex1.GetElement_Id(webBrowser1, "QM_334_Accessory_TA");
            HtmlElement SubmitBtn = ex1.GetElement_Id(webBrowser1, "QM_334_Accessory_SubmitBTN");
            if (TestArea != null && SubmitBtn != null)
            {
                ex1.Write_value(TestArea, content);
                Thread.Sleep(100);
                ex1.Btn_click(SubmitBtn, "click");
                Thread.Sleep(200);
            }
        }
        #endregion

        #region background worker
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 1; i <= regedit.VisitCount; i++)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // 执行计时操作并且报告进度
                    Random ro = new Random();
                    int qqnumber = (i == 1) ? 165501809 : ro.Next(100100100, 900900900);
                    string qzoneUrl = "http://user.qzone.qq.com/" + qqnumber.ToString();
                    worker.ReportProgress(i);// 执行计时操作并且报告进度
                    //urlAddress.Text = qzoneUrl;
                    this.webBrowser1.Navigate(qzoneUrl);
                    
                    // 等待响应
                    Thread.Sleep(ro.Next(5000, 10000));

                    //to do list
                    if ((this.webBrowser1.Url.ToString().Contains("newlimit")) && (i != 1))
                    {
                        //如果不能访问，则不计数
                        i--;
                    }
                    else
                    {
                        worker.ReportProgress(i);
                        Thread.Sleep(100);
                        this.Invoke(new submitMessage_dg(submitMessage));
                        Thread.Sleep(ro.Next(6000, 10000));
                    }
                }
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            statusLabel.Text = e.ProgressPercentage.ToString();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                statusLabel.Text = "Canceled!";
            }
            else if (e.Error != null)
            {
                statusLabel.Text = "Error: " + e.Error.Message;
            }
            else
            {
                //statusLabel.Text = "Done!";
                StartButton.Enabled = true;
                webBrowser1.Navigate("http://www.cnblogs.com/txw1958/articles/QZoneMessager.html");
            }

        }
        #endregion

        #region webbrowser
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (start)
            {
                logger(this.webBrowser1.Url.ToString());            //记录
            }
            //urlComboBox.Text = this.webBrowser1.Url.ToString(); //地址栏
            this.Text = webBrowser1.DocumentTitle;              //标量

            //HtmlDocument log_auto = webBrowser1.Document;
            //HtmlElement log_btn = null;
            //foreach (HtmlElement em in log_auto.All) //轮循
            //{
            //    string str = em.Name;
            //    string id = em.Id;
            //    listBox1.Items.Add(em.Name + em.Id);
            //}
            


        }
        private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }
        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            urlComboBox.Text = this.webBrowser1.Url.ToString();
        }
        #endregion

        #region tool button
        private void urlComboBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                webBrowser1.Navigate(urlComboBox.Text);
            }
        }
        private void RefreshButton_Click(object sender, EventArgs e)
        {
            this.webBrowser1.Refresh();
        }
        private void StopButton_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.WorkerSupportsCancellation == true)
            {
                // 取消异步操作
                backgroundWorker1.CancelAsync();
            }
            this.StartButton.Enabled = true;
        }
        private void StartButton_Click(object sender, EventArgs e)
        {
            start = true;
            if (backgroundWorker1.IsBusy != true)
            {
                // 启动异步操作
                backgroundWorker1.RunWorkerAsync();
            }
            this.StartButton.Enabled = false;
        }
        private void statusLabel_Click(object sender, EventArgs e)
        {
            //webBrowser1.Navigate("http://165501809.qzone.qq.com");

        }
        #endregion

        #region record
        private void WelcomeMessage()
        {
            logger("欢迎使用QQ空间留言器！");
            logger("使用方法：");
            logger("  1. 在上面打开的QQ空间中登录。");
            logger("  2. 修改左侧的留言内容。");
            logger("  3. 点击地址栏的绿色 ▶启动 按钮。");
        }
        private void logger(string log)
        {
            DateTime currentTime = DateTime.Now;
            this.listBox1.Items.Add(currentTime.ToString("G") + "    " + log);
            this.listBox1.TopIndex = this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight);
        }
        #endregion

        #region regedit
        private void RegeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox1 aboutBox = new AboutBox1();
            aboutBox.ShowDialog();
        }
        #endregion


    }
}
